package com.app.core.web.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.app.core.common.Result;
import com.app.core.common.ResultCode;
import com.app.core.exception.BizException;
import com.app.core.validator.ValidateMsgException;
import com.app.core.web.util.AppStringUtils;

/**
 * 全局异常拦截处理
 * 
 * @since v#{version}
 * @author zhangxf
 * @created 2015年10月26日 下午5:37:30
 */
public class AppException extends SimpleMappingExceptionResolver {

    private static final Logger log = LoggerFactory.getLogger(AppException.class);

    /* 需要返回json数据的路径 */
    private String[] jsonDataUrlPrifix;
    /* 存储生成后的正则表达式 */
    private static String jsonDataUrlPrifixRegex = null;

    public void init() {
        /* 初始化正则表达式 */
        jsonDataUrlPrifixRegex = AppStringUtils.createStartWithReg(jsonDataUrlPrifix);
    }

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {

        if (ex instanceof ValidateMsgException) {
            try {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(Result.error(ResultCode.PARAM_VALIDATE_ERROR_TIP)
                    .setData(((ValidateMsgException) ex).getResult()).toJson());
                return new ModelAndView();
            } catch (IOException e) {
                log.error("exception ", e);
            }
        }

        log.error("exception ", ex);

        /*
         * http rest接口请求
         */
        if (jsonDataUrlPrifixRegex != null
            && request.getRequestURI().replace(request.getContextPath(), "").matches(jsonDataUrlPrifixRegex)) {
            if (ex instanceof BizException) {
                outJson(response, ex.getMessage());
            } else {
                outJson(response, null);
            }
            return new ModelAndView();
        }

        /*
         * ajax请求
         */
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)) {
            if (ex instanceof BizException) {
                outJson(response, ex.getMessage());
            } else {
                outJson(response, null);
            }
            return new ModelAndView();
        }

        // ModelAndView modelAndView = new ModelAndView();
        // modelAndView.addObject("error", ex.getLocalizedMessage());
        // modelAndView.addObject("e", ex.fillInStackTrace());
        // modelAndView.addObject("ex", ex);
        // modelAndView.setViewName("/error");
        // return modelAndView;

        /*
         * 网页请求或其他异常不做处理， 通过配置web.xml 404或ngix解决
         */
        return super.doResolveException(request, response, handler, ex);
    }

    private void outJson(HttpServletResponse response, String msg) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=UTF-8");
            if (StringUtils.isBlank(msg)) {
                response.getWriter().write(Result.error(ResultCode.SERVER_INNER_ERROR).toJson());
            } else {
                response.getWriter().write(Result.error(msg).toJson());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String[] getJsonDataUrlPrifix() {
        return jsonDataUrlPrifix;
    }

    public void setJsonDataUrlPrifix(String[] jsonDataUrlPrifix) {
        this.jsonDataUrlPrifix = jsonDataUrlPrifix;
    }

}
